package com.netease.cloud.cm.util;

import com.google.common.io.Files;
import org.testng.util.Strings;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GetEnvConfig {

    public static String getPath() {
        File filePath;
        if (Strings.isNotNullAndNotEmpty(System.getProperty("work.dir")) || GetEnvConfig.class.getResource("/") == null) {
            filePath = new File(System.getProperty("work.dir"));
        } else {
            filePath = new File(GetEnvConfig.class.getResource("/").getPath());
        }
        return filePath.toString();
    }

    private static List<String> getFileContent(File file) {
        try {
            List<String> list = Files.readLines(file, Charset.forName("UTF-8"));
            List<String> retList = new ArrayList<String>(list.size());

            for (String line : list) {
                line = line.trim();
                if (line.startsWith("#") || "".equals(line)) {
                    continue;
                }
                retList.add(line);
            }
            return retList;
        } catch (IOException e) {
            e.printStackTrace();
            return Collections.EMPTY_LIST;
        }
    }

    public static String getEnv() {

        // 获取环境配置文件的路径
        String env = System.getProperty("env");
        System.out.println("get env from ENV: " + env);
        if (Strings.isNotNullAndNotEmpty(env)) {
            return env;
        }

        // 获取环境配置文件的路径
        String configPath = getPath() + "/configEnv";
        System.out.println(configPath);
        env = null;
        BufferedReader br = null;

        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(configPath)));
            env = br.readLine().trim();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return env;
    }

    // 获取配置文件所在的路径
    public String getEnvConfig() {
        // 组装配置的文件的路径
        return getPath() + "/conf/" + getEnv() + ".properties";
    }

    public static void main(String[] args) {
        System.out.println(GetEnvConfig.getEnv());
    }
}

